package com.zwface.demo.http;


import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.zwface.demo.App;
import com.zwface.demo.comm.comm;
import com.zwface.demo.function.login.LoginActivity;
import com.zwface.demo.model.ErrorInfo;
import com.zwface.demo.utils.DialogHelper;
import com.zwface.demo.utils.FastjsonHelper;
import com.zwface.demo.utils.SharedPreferenceUtils;

import org.apache.http.Header;

import java.util.HashMap;
import java.util.Map;

/**
 * 网络请求回调封装
 * 处理回调码等
 */
public class ZwAsyncHttpResponseHandler extends AsyncHttpResponseHandler
{
    private HttpCallback callback;
    private String url,paramStr;//打印日志需要

    public ZwAsyncHttpResponseHandler(HttpCallback callback,String url,String paramStr) {
        this.callback = callback;
        this.url = url;
        this.paramStr = paramStr;
    }

    @Override
    public void onSuccess(int i, Header[] headers, byte[] bytes) {
        try {
            String s = new String(bytes,"UTF-8");
            LogUtils.d("网络请求--"+url+"\n"+paramStr+"\n"+s);
            ErrorInfo errorInfo = FastjsonHelper.deserialize(s, ErrorInfo.class);
            switch (errorInfo.getCode()){
                case comm.RES_STATUS_OK:
                    callback.OnSuccess(i, StringUtils.isEmpty(errorInfo.getMessage())?comm.RES_ERROR_UNKNOWN:errorInfo.getMessage());
                    break;
                case comm.RES_STATUS_ERROR_TO_LOGIN:
                    ActivityUtils.startActivity(LoginActivity.class);
                    break;
                default:
                    callback.OnFailure(i, StringUtils.isEmpty(errorInfo.getMessage())? comm.RES_ERROR_UNKNOWN:errorInfo.getMessage());
                    break;
            }
        }catch (Exception e){
            callback.OnFailure(i, comm.RES_ERROR_UNKNOWN);
        }
    }

    @Override
    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
        try {
            //{"timestamp":"2019-10-25 11:21:25","status":400,"error":"Bad Request","message":"Bad Request","path":"/sms/send"}
            String s = new String(bytes);
            LogUtils.d("网络请求--"+url+"\n"+paramStr+"\n"+s);
            ErrorInfo errorInfo = FastjsonHelper.deserialize(s, ErrorInfo.class);
            switch (errorInfo.getCode()){
                case comm.RES_STATUS_ERROR_TO_LOGIN:
                    ActivityUtils.startActivity(LoginActivity.class);
                    break;
                case comm.RES_STATUS_ERROR_ACCESS_TOKEN://accesstoken失效刷新token
                    callback.OnFailure(i, errorInfo.getMessage());
                    refreshToken();
                    break;
                case comm.RES_STATUS_ERROR_REFRESH_TOKEN://refreshtoken失效去登陆
                    callback.OnFailure(i, errorInfo.getMessage());
                    DialogHelper.showInvalidTokenDialog(errorInfo.getMessage());
                    break;
                default:
                    callback.OnFailure(i, StringUtils.isEmpty(errorInfo.getMessage())? comm.RES_ERROR_UNKNOWN:errorInfo.getMessage());
                    break;
            }

            callback.OnFailure(i, StringUtils.isEmpty(errorInfo.getMessage())? comm.RES_ERROR_UNKNOWN:errorInfo.getMessage());
        }catch (Exception e){
            callback.OnFailure(i, comm.RES_ERROR_UNKNOWN);
        }
    }

    /**
     * 刷新token
     */
    private void refreshToken()
    {
        ToastUtils.cancel();
        Map<String,String> map = new HashMap<>();
        map.put("prodId","18");
        String refreshToken = SharedPreferenceUtils.getParam(App.getInstance().getApplicationContext(),SharedPreferenceUtils.REFRESH_TOKEN);
        String url = comm.API_GET_REFRESH_TOKEN+"?grant_type=refresh_token&refresh_token="+refreshToken+"&client_id=mobile&client_secret=mobile";
        ZWAsyncHttpClient.post(url, map, new HttpCallback() {
            @Override
            public void OnSuccess(int i, String res) {
                //{"access_token":"f0f7809e-cc47-4310-bb72-1d4a5dec886a","token_type":"bearer","refresh_token":"950b805e-d08e-4e88-b269-dbe30375ba15","expires_in":1799,"userId":"12"}
                LogUtils.d(res);
                JSONObject object = JSONObject.parseObject(res);
                String access_token = object.getString("access_token");
                String refresh_token = object.getString("refresh_token");
                SharedPreferenceUtils.setParam(App.getInstance().getApplicationContext(),SharedPreferenceUtils.ACCESS_TOKEN,access_token);
                SharedPreferenceUtils.setParam(App.getInstance().getApplicationContext(),SharedPreferenceUtils.REFRESH_TOKEN,refresh_token);
            }

            @Override
            public void OnFailure(int i, String res) {
            }
        });
    }

}
